package cn.creditease.std.utils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description: 线程池配置
 * @Author: kai.yang
 * @Date: 2019-08-07 14:48
 */
public class ThreadPoolUtils {

    private static ExecutorService threadPool;


    // 保持最少corePoolSize个线程
    // 最佳线程数目 = （线程等待时间与线程CPU时间之比 + 1）* CPU数目,
    private static int corePoolSize = 10;

    // 如果corePoolSize都在工作，新任务放入到queue中等待
    private static int waitQueueSize = 2000;

    // 如果queue中等待任务已满，则继续创建新线程处理任务,如果工作线程数达到maxPoolSize依然不够处理，则拒绝最新的请求(本处将抛出异常)
    private static int maxPoolSize = 20;

    // 空闲线程存活时间,根据定时分布配置
    private static long threadLiveTime = 5;

    private static AtomicBoolean initFlag = new AtomicBoolean(false);

    /* 任务处理线程池 */
    public static ExecutorService getThreadPool() {
        return getThreadPool(corePoolSize, maxPoolSize, waitQueueSize);
    }

    public static ExecutorService getThreadPool(int corePoolSize, int maxPoolSize, int waitQueueSize) {
        if (!initFlag.get()) {
            synchronized (ThreadPoolUtils.class) {
                if (!initFlag.get()) {
                    ArrayBlockingQueue waitQueue = new ArrayBlockingQueue(waitQueueSize);
                    threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, threadLiveTime,
                        TimeUnit.MINUTES, waitQueue, new ThreadPoolExecutor.AbortPolicy());
                    initFlag.set(true);
                }
            }
        }
        return threadPool;
    }

}
